/*
 * Designed and developed by 2017 skydoves (Jaewoong Eum)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.skydoves.colorpickerview;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Shader;
import android.graphics.LinearGradient;
import android.graphics.drawable.BitmapDrawable;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * ColorLinearPalette is a custom drawable palette built with linear gradient
 * for displaying a rainbow color strip effect.
 */
public class ColorLinearPalette extends BitmapDrawable {

  private final Paint paint;
  private float radius = 0f; // 圆角半径，默认为0（直角）
  
  /**
   * 设置线性调色板的圆角半径
   * @param radius 圆角半径值
   */
  public void setRadius(float radius) {
    this.radius = radius;
  }
  
  /**
   * 获取线性调色板的圆角半径
   * @return 当前圆角半径值
   */
  public float getRadius() {
    return radius;
  }

  public ColorLinearPalette(Resources resources, Bitmap bitmap) {
    super(resources, bitmap);
    this.paint = new Paint(Paint.ANTI_ALIAS_FLAG);
  }

  @Override
  public void draw(@NonNull Canvas canvas) {
    int width = getBounds().width();
    int height = getBounds().height();

    // 创建彩虹色的线性渐变
    Shader linearShader = new LinearGradient(
        0, 0, width, 0,  // 水平渐变从左到右
        new int[] {
            Color.RED,
            Color.YELLOW,
            Color.GREEN,
            Color.CYAN,
            Color.BLUE,
            Color.MAGENTA,
            Color.RED
        },
        new float[] {
            0.0f,
            0.166f,
            0.333f,
            0.5f,
            0.666f,
            0.833f,
            1.0f
        },
        Shader.TileMode.CLAMP
    );

    paint.setShader(linearShader);
    // 根据是否设置了圆角来决定绘制方式
    if (radius > 0) {
      // 绘制圆角矩形
      canvas.drawRoundRect(0, 0, width, height, radius, radius, paint);
    } else {
      // 绘制普通矩形
      canvas.drawRect(0, 0, width, height, paint);
    }
  }

  @Override
  public void setAlpha(int alpha) {
    paint.setAlpha(alpha);
  }

  @Override
  public void setColorFilter(@Nullable ColorFilter colorFilter) {
    paint.setColorFilter(colorFilter);
  }

  @Override
  public int getOpacity() {
    return PixelFormat.OPAQUE;
  }
}